<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class BackEndController extends MY_Controller {
    public $user_id;
    public $image_folder;
    public $role;

    public function __construct() {
        parent::__construct();
        $this->user_id = $this->session->userdata('user_id');

        if(!$this->user_id) {
            if ($this->input->is_ajax_request()) {
                $a = array('code' => E_SESSION_TIMEOUT, 'login_href' => page_url('dang-nhap'));
                echo json_encode($a);
                die();
            } else {
                redirect(page_url('dang-nhap'));
            }
        }
        $this->role         = $this->session->userdata('role');
        $this->image_folder = $this->session->userdata('image_folder');
        $this->checkRole();
        $this->lang->load('error', 'vietnamese');
        $this->lang->load('form_validation', 'vietnamese');
        $this->load->library('form_validation');
        $this->load->model('repo/contact_model', 'contact_model');
    }

    public function loadView($layout, $viewName, $data) {
        switch ($this->role) {
            case ROLE_ADMIN:
            $data['role_folder'] = 'admin';
            break;
            case ROLE_MOD:
            $data['role_folder'] = 'mod';
            break;
            case ROLE_SHOP_OWNER:
            $data['role_folder'] = 'shop';
            break;
            case ROLE_ADVERTISER:
            $data['role_folder'] = 'user';
            break;
            default:
            break;
        }
        $data['aTopContact'] = $this->contact_model->paging(
            $this->user_id, CONTACT_TOP_LIMIT, 0, array('a.message'), array('a.unread'=>1)
            );
        $data['pageHtml'] = $this->load->view($viewName . '.html.php', $data, true);
        $this->load->view($layout.'.html.php', $data);
    }

    public function alpha_numeric_space($str) {
        if (preg_match('/^[a-zA-Z0-9 ]+$/', $str) == 1) {
            return true;
        }
        return false;
    }

    public function repassword_check($str) {
        $password = '';
        if($this->input->post('signup', true)!=false){
            $password = $this->input->post('signup', true);
        }
        if($this->input->post('re', true)!=false){
            $password = $this->input->post('re', true);
        }
        if ($str != $password['password']) {
            return false;
        }
        return true;
    }

    public function start_date_check($str) {
        $d = explode('-', $str);
        if(count($d)!=3){
            return false;
        } else {
            return checkdate($d[1], $d[2], $d[0]);
        }
        return false;
    }

    public function end_date_check($str, $startdate) {
        $enddate = new DateTime($str);
        $startdate = new DateTime($startdate);
        if ($enddate !== false) {
            if ($startdate < $enddate) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    public function anchor_check($str) {
        if ($str!='' && !filter_var($str, FILTER_VALIDATE_URL)) {
            return false;
        }
        return true;
    }

    public function slug_check($str) {
        if(strlen($str) > 150 || $str==''){
            return false;
        } else {
            if (preg_match('/^[a-z\-0-9]+$/', $str)) {
                return true;
            }
        }

        return false;
    }

    public function username_check($username) {
        if(preg_match('/^[A-Za-z0-9_]+$/', $username)) {
            return true;
        }
        return false;
    }

    public function blank_numeric_check($str) {
        if($str!=''){
            return is_numeric($str);
        }
        return true;
    }

    public function check_image_exist($str) {
        $a = explode('/', $str);
        if (count($a) != 2) {
            return false;
        } else {
            $file_path = "";
            if ($a[0] == 'temp') {
                //check temp
                $file_path = FCPATH . 'uploads/public/' . $this->image_folder . '/' . TEMP_FOLDER_URL . $a[1];
            } elseif ($a[0] == 'post') {
                //check post
                $file_path = FCPATH . 'uploads/public/' . $this->image_folder . '/' . POST_IMAGE_URL . $a[1];
            } elseif ($a[0] == 'category') {
                //check category
                $file_path = FCPATH . 'uploads/public/' . $this->image_folder . '/' . CATEGORY_IMAGE_URL . $a[1];
            }
            if (file_exists($file_path)) {
                return true;
            }
            return false;
        }
    }

    public function upload() {
        $config['allowed_types'] = 'jpg|png';
        $config['max_size']      = '5000';
        $config['max_width']     = '5000';
        $config['max_height']    = '5000';
        $config['encrypt_name']  = true;
        $config['remove_spaces'] = true;

        $path = './uploads/public/'.$this->image_folder.'/uploaded/';
        if(!file_exists($path)){
            mkdir($path, 0777, true);
        } else {
            //delete all temp inside uploaded
            //array_map('unlink', glob($path."*.*"));
        }
        $config['upload_path'] = $path;

        $aResult = array();
        $this->load->library('upload', $config);
        if (!$this->upload->do_upload()) {
            $error = array('error' => $this->upload->display_errors());
            $aResult = array('code' => 0, 'error' => $error);
        } else {
            $upload_data = $this->upload->data();
            $file_path = base_url($path.$upload_data['file_name'], false);
            $aResult = array(
                'code' => 1,
                'file_name' => $upload_data['file_name'],
                'file_path' => $file_path);
        }
        $this->renderJSON($aResult);
    }

    public function deleteUpload(){
        $aResult = array();
        $folder  = $this->input->post('folder', true);
        $name    = $this->input->post('name', true);
        $path    = UPLOAD_FOLDER_URL . 'public/' . $this->image_folder . '/' . $folder . '/' . $name;
        if(file_exists($path)){
            //remove thumbs if exists
            $pathThumb = UPLOAD_FOLDER_URL . 'public/' . $this->image_folder . '/' . $folder . '/' . thumb_name($name);
            if(file_exists($pathThumb)){
                unlink($pathThumb);
            }
            $b = unlink($path);
            if($b){
                $aResult['code'] = 1;
            } else {
                $aResult['code'] = 0;
                $aResult['msg']  = $this->lang->line('delete_image_fail');
            }
        } else {
            $aResult['code'] = 0;
            $aResult['msg']  = $this->lang->line('delete_image_fail');
        }
        $this->renderJSON($aResult);
    }

    public function cropUpload(){
        $this->load->library('MyImage', 'myimage');
        $image       = $this->input->post('crop');
        $temp_path   = 'uploads/public/'.$this->image_folder.'/uploaded/'.$image['path'];
        $screen_dim  = array('width'=>$image['screen_width']);
        $scaled      = array(
            'width'  => $image['w'],
            'height' => $image['h'],
            'x1'     => $image['x1'],
            'y1'     => $image['y1'],
            );
        $new_dim        = array('width'=>$image['screen_width'], 'thumb_width'=>$image['thumb_width']);
        $new_thumb_path = 'uploads/public/'.$this->image_folder.'/'.TEMP_FOLDER_URL.thumb_name($image['path']);
        $this->myimage->create_thumbnail($temp_path, $screen_dim , $scaled, $new_dim, $new_thumb_path);

        // move image from uploaded to temp
        copy('uploads/public/'.$this->image_folder.'/uploaded/'.$image['path'], 'uploads/public/'.$this->image_folder.'/'.TEMP_FOLDER_URL.$image['path']);
        unlink('uploads/public/'.$this->image_folder.'/uploaded/'.$image['path']);

        //render result
        $this->renderJSON(
            array(
                'file_name'     => $image['path'],
                'file_path'     => upload('public/'.$this->image_folder.'/'.TEMP_FOLDER_URL.thumb_name($image['path']), false),
                'file_org_path' => upload('public/'.$this->image_folder.'/'.TEMP_FOLDER_URL.$image['path'], false)
                )
            );
    }

    public function moveUpload($image){
        // move image from uploaded to temp
        copy('uploads/public/'.$this->image_folder.'/uploaded/'.$image['path'], 'uploads/public/'.$this->image_folder.'/'.$image['dest_path']);
        unlink('uploads/public/'.$this->image_folder.'/uploaded/'.$image['path']);
    }
}
?>